import React from 'react';
import { Breadcrumb, Icon, Button, Table, Modal, Input, Select, Pagination, message ,Row,Col,DatePicker,Form,Checkbox,AutoComplete,InputNumber,Upload } from 'antd';
import $ from 'jquery';
import Config from '../../common/config';
import convertCurrency from '../commonFunction/convertCurrency';
import getFormatDate from '../commonFunction/getFormatData';
import moment from 'moment';
import noRepeat from '../commonFunction/noRepeat';
const config = new Config();
const { RangePicker } = DatePicker;
const { TextArea } = Input;
const FormItem = Form.Item;
const Option = Select.Option;
const userInfo = JSON.parse(sessionStorage.getItem('UserInfo')); //用户信息
const root = userInfo.root;
class ChannelManage1 extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            dateStr:['',''],//默认今天的日期字符串
            date:['',''],//默认今天的日期
            channelList: [],//申请列表
            channelcount: 0,//申请列表条数
            pageindex:1,//当前页码
            selectedProduct:'',//筛选产品
            selectedUmbrellaName:'',//筛选平台
            applyPeopleName:'',//筛选负责人姓名
            selectionList:[[],[],[],[]],//筛选列表
            selectedRows:[],//打印选中的列表
            authTreeOfOne:{},//
            channelList2:[{}]//
        }
    }
    componentWillMount(){
        console.log(userInfo.auth);
        if(userInfo.auth){
            if(userInfo.auth['橘色小工具']){
                this.setState({
                    authTreeOfOne:userInfo.auth['橘色小工具']
                },()=>{
                    console.log(this.state.authTreeOfOne['/payrequest/save']);
                })
            }
        }


    }
    componentDidMount() {
        //筛选列表
        let selectionList=[[],[],[],[]];
        const {authTreeOfOne}=this.state;
        let url='';
        if(authTreeOfOne['/budget/findonesource']){
            url=`${config.juseLittleTool}/budget/findonesource`
        }
        if(root||(authTreeOfOne['/budget/findsource'])){
            url=`${config.juseLittleTool}/budget/findsource`
        }
        $.ajax({
            url: url,
            type: "post",
            async: true,
            headers: {
                'Authorization': 'Bearer ' + sessionStorage.getItem('token'),
            },
            //data:{user:sessionStorage.getItem('token'),},
            success: data => {
                console.log(data);
                if (data.code === 200) {
                    const List = data.data;
                    if (List.length > 0) {
                        List.forEach((ele, i) => {
                            selectionList[0].push(ele.product);  //产品
                            selectionList[1].push(ele.umbrellaname);//平台
                            selectionList[2].push(ele.channelname);//账户名
                            selectionList[3].push(ele.personincharge);//申请人
                        });
                        this.setState({
                            selectionList:[noRepeat(selectionList[0]),noRepeat(selectionList[1]),noRepeat(selectionList[2]),noRepeat(selectionList[3]),],
                            alreadyGetSelectionList:true,
                        },()=>{
                            console.log(this.state.selectionList);
                        })
                    }

                }
            }
        });
        //初始化时间
        let dateStr=getFormatDate(new Date());
        this.setState({
            dateStr:[dateStr,dateStr],
            date:[moment(dateStr),moment(dateStr)],
        });
        this.getBannerList(1,dateStr,dateStr);
    }
    //日期筛选方法
    changeDate(date, dateStr) {
        this.setState({
            dateStr,
            date,
        });
        this.setState({
            pageindex:1,
        });
        const { selectedProduct,selectedUmbrellaName,applyPeopleName}=this.state;
        this.getBannerList(1,dateStr[0],dateStr[1],selectedProduct,selectedUmbrellaName,applyPeopleName);
    }
    //生日禁用
    disabledDate(val) {
        if (val) {
            return val.valueOf() > Date.now();
        } else {
            return false;
        }
    }

    //获取申请列表  starttime, endtime, product（产品）, umbrellaname（平台）, state, people（负责人）, pagesize, pageindex
    getBannerList(pageindex,starttime, endtime,product,umbrellaname,people) {
        const {authTreeOfOne}=this.state;
        let url='';
        if(authTreeOfOne['/budget/findonelist']){
            url=`${config.juseLittleTool}/budget/findonelist`
        }
        if(root||(authTreeOfOne['/budget/findlist'])){
            url=`${config.juseLittleTool}/budget/findlist`
        }
        $.ajax({
            url:url,
            type: "post",
            async: true,
            headers: {
                'Authorization': 'Bearer ' + sessionStorage.getItem('token'),
            },
            data:{
                //user:sessionStorage.getItem('token'),
                pagesize:15,
                pageindex,
                starttime,
                endtime,
                product,//产品
                umbrellaname,//平台
                people,//申请人
            },
            success: data => {
                console.log(data);
                let channelList2=[];
                let budgetrecharge = 0;//预算充值总额
                let practicalrecharge=0; //实际充值总额
                let balance=0;  //余额
                let budgetcoilln = 0;//预计进线
                let budgetcoillnmoney = 0;//预计进线成本
                let outputratio=0;//产出比
                let recyclesum=0;//复购总值
                let index=0;
                if (data.code === 200) {
                    const channelList = data.data.rows;
                    if (channelList.length > 0) {
                        channelList.forEach((ele, i) => {
                             ele.index = i + 1;
                             budgetrecharge += ele.budgetrecharge*1;//预算充值总额
                             practicalrecharge +=ele.practicalrecharge*1; //实际充值总额
                             balance+=ele.balance*1;  //余额
                             budgetcoilln += ele.budgetcoilln*1;//预计进线
                             budgetcoillnmoney += ele.budgetcoillnmoney*1;//预计进线成本
                             outputratio +=ele.outputratio*1;//产出比
                             recyclesum += ele.recyclesum*1;//复购总值
                             index=i+2;
                        });
                        channelList2.push({index:index,createtime:'总计',budgetrecharge:budgetrecharge.toFixed(2),
                            practicalrecharge:practicalrecharge.toFixed(2),balance:balance.toFixed(2),
                            budgetcoilln:budgetcoilln,budgetcoillnmoney:budgetcoillnmoney.toFixed(2),
                            recyclesum:recyclesum.toFixed(2)})
                        this.setState({
                            channelList,
                            channelList2,
                            channelcount: data.data.count,
                        });
                    }else{
                        this.setState({
                            channelList:[],
                            channelcount: 0,
                        });
                    }
                } else {
                    message.error(`${data.mes} 请返回重新操作`, 2);
                }
            }
        });
    }
    //分页
    changePage(pageindex) {
        this.setState({
            pageindex
        });
        const { dateStr,selectedProduct,selectedUmbrellaName,applyPeopleName}=this.state;
        this.getBannerList(pageindex,dateStr[0],dateStr[1],selectedProduct,selectedUmbrellaName,applyPeopleName);
    }

    //筛选查询
    doSearch(){
        this.setState({
            pageindex:1,
        });
        const { dateStr,selectedProduct,selectedUmbrellaName,applyPeopleName}=this.state;
        this.getBannerList(1,dateStr[0],dateStr[1],selectedProduct,selectedUmbrellaName,applyPeopleName);
    }

    //筛选方法
    handleApplyState(state,value){
        console.log(state);
        this.setState({
            pageindex:1,
        });
        const { dateStr,selectedProduct,selectedUmbrellaName,applyPeopleName}=this.state;
        if(state===1){
            this.setState({
                selectedProduct:value,
            })
            this.getBannerList(1,dateStr[0],dateStr[1],value,selectedUmbrellaName,applyPeopleName);
        }else if(state===2){
            this.setState({
                selectedUmbrellaName:value,
            })
            this.getBannerList(1,dateStr[0],dateStr[1],selectedProduct,value,applyPeopleName);
        }else{
            this.setState({
                applyPeopleName:value,
            })
            this.getBannerList(1,dateStr[0],dateStr[1],selectedProduct,selectedUmbrellaName,value);
        }
    }

    //打印
    handlePrint(){
        this.printpage();
    }
    printpage() {
        let newstr = `
            <table class="" >
              <caption>预算列表</caption>
                  <thead>
                    <tr>
                      <td>时间</td>
                      <td>产品</td>
                      <td>品台</td>
                      <td>账户名</td>
                      <td>预算充值金额</td>
                      <td>实际充值金额</td>
                      <td>余额</td>
                      <td>预计消费</td>
                      <td>预计进线</td>
                      <td>预计进线成本</td>
                      <td>产出比</td>
                      <td>复购总值</td>
                      <td>备注</td>
                      <td>负责人</td>
                    </tr>
                  </thead>
          <tbody>`;
        newstr += this.printHtml();
        newstr += `</tbody></table>`;
        let wind = window.open("", "newWindow");
        let styleNode=document.createElement('style');
        styleNode.innerHTML=`	table{
        border-collapse: collapse;
        width:100%;
        font-size:12px;
      }
      td {
        text-align:center;
        border: 1px solid #ddd;
      }`;
        wind.document.getElementsByTagName('head')[0].appendChild(styleNode);
        wind.document.body.innerHTML = newstr;
        wind.print();
    }
    printHtml() {
        let str = '';
        let budgetrecharge = 0;//预算充值总额
        let practicalrecharge=0; //实际充值总额
        let balance=0;  //余额
        let budgetcoilln = 0;//预计进线
        let budgetcoillnmoney = 0;//预计进线成本

        let recyclesum=0;//复购总值
        let rows=[];
        if(this.state.selectedRows.length>0){
            rows=this.state.selectedRows;
        }else{
            rows=this.state.channelList;
        }
        rows.map(item => {
            budgetrecharge += item.budgetrecharge*1;//预算充值总额
            practicalrecharge +=item.practicalrecharge*1; //实际充值总额
            balance+=item.balance*1;  //余额
            budgetcoilln += item.budgetcoilln*1;//预计进线
            budgetcoillnmoney += item.budgetcoillnmoney*1;//预计进线成本

            recyclesum += item.recyclesum*1;//复购总值
            str += `<tr>
                <td>${item.createtime}</td>
                <td>${item.product==undefined?'':item.product}</td>
                <td>${item.umbrellaname==undefined?'':item.umbrellaname}</td>
                <td>${item.account==undefined?'':item.account}</td>
                <td>${item.budgetrecharge==null?'':item.budgetrecharge}</td>
                <td>${item.practicalrecharge==null?'':item.practicalrecharge}</td>
                <td>${item.balance==null?'':item.balance}</td>
                <td>${item.budgetmoney==null?'':item.budgetmoney}</td>
                <td>${(item.budgetcoilln=='NaN')?'':item.budgetcoilln}</td>
                <td>${item.budgetcoillnmoney==null?'':item.budgetcoillnmoney}</td>
                <td>${item.outputratio==='NaN'||item.outputratio==undefined?'':item.outputratio}</td>
                <td>${item.recyclesum==null?'':item.recyclesum}</td>
                <td>${item.remark==null?'':item.remark}</td>
                <td>${item.personincharge==undefined?'':item.personincharge}</td>
            </tr>`;
        });
        str += `<tr>
                <td>总计</td>
                <td></td>
                <td></td>
                <td></td>
                <td>${budgetrecharge==null?'':budgetrecharge.toFixed(2)}</td>
                <td>${practicalrecharge==null?'':practicalrecharge.toFixed(2)}</td>
                <td>${balance==null?'':balance.toFixed(2)}</td>
                <td></td>
                <td>${(budgetcoilln=='NaN')?'':budgetcoilln}</td>
                <td>${budgetcoillnmoney==null?'':budgetcoillnmoney.toFixed(2)}</td>
                <td></td>
                <td>${recyclesum==null?'':recyclesum.toFixed(2)}</td>
                <td></td>
                <td></td>
            </tr>`;
        return str;
    }
    //导出
    downList() {
        console.log(this.state.selectedRows);
        const { dateStr,selectedProduct,selectedUmbrellaName,applyPeopleName}=this.state;
        let url=`${config.juseLittleTool}/budget/downloadExcel `;
        //console.log(url);
        let para;
        if(this.state.selectedRows.length>0){
            para={
                datasource:JSON.stringify(this.state.selectedRows),
            }
        }else{
            para={
                starttime:dateStr[0],
                endtime:dateStr[1],
                product:selectedProduct,//产品
                umbrellaname:selectedUmbrellaName,//平台
                people:applyPeopleName,//申请人
            };
        }
        $.ajax({
            url:url,
            type: "post",
            headers: { Authorization: 'Bearer '+sessionStorage.getItem('token')},
            data:para,
            async: true,
            success: (data)=> {
                console.log(data);
                if(data.code===200){
                    window.location=`${config.juseLittleTool}/channel/download?name=`+data.downloadExcel;
                }
            }
        });
    }

    render() {
        //费用预览表格
        const data = [
            {
                title: '时间',
                dataIndex: 'createtime',
                width: 170,
            },{
                title: '产品',
                dataIndex: 'product',
                width: 120,
            },{
                title: '平台',
                dataIndex: 'umbrellaname',
                width: 120,
            },{
                title: '账户名',
                dataIndex: 'account',
                width: 120,
            },{
                title: '预算充值金额',
                dataIndex: 'budgetrecharge',
                width: 100,
            },{
                title: '实际充值金额',
                width: 100,
                dataIndex: 'practicalrecharge',
            }, {
                title: '余额',
                width: 100,
                dataIndex: 'balance',
            } , {
                title: '预计消费',
                width: 100,
                dataIndex: 'budgetmoney',
            } ,{
                title: '预计进线',
                width: 100,
                dataIndex: 'budgetcoilln',
            },{
                title: '预计进线成本',
                width: 100,
                dataIndex: 'budgetcoillnmoney',
            },{
                title: '产出比',
                width: 100,
                dataIndex: 'outputratio',
            },{
                title: '复购总值',
                width: 100,
                dataIndex: 'recyclesum',
                render:text=><span>{text==='NaN'?'':text}</span>
            },{
                title: '备注',
                width: 200,
                dataIndex: 'remark',
            },{
                title: '负责人',
                width: 100,
                dataIndex: 'personincharge',
            },
        ];
        const rowSelection = {
            onChange: (selectedRowKeys, selectedRows) => {
                // console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows,this.state.feePreviewData);
                this.setState({
                    selectedRows:selectedRows,
                });
            },
            getCheckboxProps: record => ({
                disabled: record.createtime === '总计', // Column configuration not to be checked
            }),
        };
        const {selectionList,channelList,channelList2}=this.state;
        return (
            <div className='goods-label clearfix'>
                {/*面包屑*/}
                < Breadcrumb separator=">" >
                    <Breadcrumb.Item>橘色小工具</Breadcrumb.Item>
                    <Breadcrumb.Item>预算管理</Breadcrumb.Item>
                    <Breadcrumb.Item>预算列表</Breadcrumb.Item>
                </Breadcrumb >
                {/*筛选条*/}
                <div style={{marginTop:'40px'}} className="clearfix">
                    <Row>
                        <Col span={7}>
                            申请时间:&nbsp;&nbsp;&nbsp;
                            <RangePicker placeholder={['请选择日期', '请选择日期']}
                                         onChange={this.changeDate.bind(this)}
                                         format='YYYY-MM-DD'
                                         value={this.state.date}
                                         style={{width:'220px'}}
                                         disabledDate={(val) => this.disabledDate(val)}
                            />
                        </Col>
                        <Col span={4}>
                            产品:&nbsp;&nbsp;&nbsp;
                            <Select  style={{width:'110px'}} onChange={this.handleApplyState.bind(this,1)} defaultValue="">
                                <Option value='' >全部</Option>
                                {selectionList[0].map(item=><Option value={item} key={item}>{item}</Option>)}
                            </Select>
                        </Col>
                        <Col span={4}>
                            平台商:&nbsp;&nbsp;&nbsp;
                            <Select  style={{width:'110px'}} onChange={this.handleApplyState.bind(this,2)} defaultValue="">
                                <Option value='' >全部</Option>
                                {selectionList[1].map(item=><Option value={item} key={item}>{item}</Option>)}
                            </Select>
                        </Col>
                        <Col span={4}>
                            申请人:&nbsp;&nbsp;&nbsp;
                            <Select  style={{width:'110px'}} onChange={this.handleApplyState.bind(this,4)} defaultValue="">
                                <Option value='' >全部</Option>
                                {selectionList[3].map(item=><Option value={item} key={item}>{item}</Option>)}
                            </Select>
                        </Col>
                        <Col span={5} >
                            <Button type="primary" onClick={this.doSearch.bind(this)}>查询</Button>
                            <Button type="primary" style={{marginLeft:'10px'}} onClick={this.handlePrint.bind(this)}>打印</Button>
                            <Button type="primary" style={{marginLeft:'10px'}} onClick={this.downList.bind(this)}>导出Excel</Button>
                        </Col>
                    </Row>
                    <div className='allgoods-table clearfix' style={{marginTop:'40px',marginBottom:'60px'}}>
                        <Table rowSelection={rowSelection}
                               rowKey="index"
                               columns={data}
                               dataSource={this.state.channelList}
                               pagination={{ pageSize: 15}}
                               bordered
                        />
                    </div>
                    <div style={{position:'fixed',bottom:'0px',paddingRight:'30px',}}>
                        { channelList.length>1?
                            <table style={{ borderCollapse:'collapse',}} className="testTable">
                                <tbody>
                                <tr>
                                    <th style={{width:'3%'}}></th>
                                    <th style={{width:'3.96%'}}>预算充值总额</th>
                                    <th style={{width:'3.96%'}}>实际充值总额</th>
                                    <th style={{width:'3.96%'}}>余额</th>
                                    <th style={{width:'3.96%'}}>预计进线</th>
                                    <th style={{width:'3.96%'}}>预计进线成本</th>
                                    <th style={{width:'3.96%'}}>复购总值</th>
                                </tr>
                                <tr>
                                    <td style={{width:'3%'}}>总计</td>
                                    <td style={{width:'3.96%'}}>{channelList2[0].budgetrecharge}</td>
                                    <td style={{width:'3.96%'}}>{channelList2[0].practicalrecharge}</td>
                                    <td style={{width:'3.96%'}}>{channelList2[0].balance}</td>
                                    <td style={{width:'3.96%'}}>{channelList2[0].budgetcoilln}</td>
                                    <td style={{width:'3.96%'}}>{channelList2[0].budgetcoillnmoney}</td>
                                    <td style={{width:'3.96%'}}>{channelList2[0].recyclesum}</td>
                                </tr>
                                </tbody>
                            </table> :''}
                    </div>

                </div>
                {/*<Row style={{marginBottom:'40px'}} align="bottom">*/}
                    {/*<Col span={10} offset={6}>*/}
                        {/*{*/}
                            {/*this.state.channelcount == 0?*/}
                                {/*<p className="floor-ppagip">*/}
                                    {/*共{this.state.channelcount}条记录*/}
                                {/*</p> :*/}
                                {/*<p className="floor-ppagip">*/}
                                    {/*当前显示*/}
                                    {/*{this.state.channelcount===0?0:(15*(this.state.pageindex-1)+1)}—*/}
                                    {/*{15*this.state.pageindex < this.state.channelcount ? 15*this.state.pageindex : this.state.channelcount}条记录，*/}
                                    {/*共{this.state.channelcount}条记录*/}
                                {/*</p>*/}
                        {/*}*/}
                        {/*<Pagination showQuickJumper  current={this.state.pageindex}  defaultPageSize={15} onChange={this.changePage.bind(this)} total={ this.state.channelcount||1}   />*/}
                    {/*</Col>*/}
                {/*</Row>*/}
            </div>
        )
    }
}
const ChannelManage = Form.create()(ChannelManage1);
export default ChannelManage;